package com.jsyh.maidu.activity.me;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jsyh.maidu.R;
import com.jsyh.maidu.config.ConfigValue;
import com.jsyh.maidu.http.HttpFormClient;
import com.jsyh.maidu.model.EvaluateModle;
import com.jsyh.maidu.model.UploadImage;
import com.jsyh.shopping.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShaidanActivity extends Activity implements View.OnClickListener{

    EvaluateModle.EvaluateMain evaluateMain;

    private SelectPhotoPopupwindow photoPopupwindow;

    ImageView iv_good,iv_shai1,iv_shai2,iv_shai3,iv_shai4,iv_back;
    TextView tv_goods,tv_title;
    Button btn_submit;
    EditText et_title,et_content;
    LinearLayout ll_main;

    private List<Bitmap> bitlist;
    private List<String> strOutpic;
    private List<byte[]> Blist;
    ImageView[] imgarray;

    int picstatic=1;

    private final int SELECT_PICTURE=1;
    private final int PHOTO_GRAPH=2;
    private final int SAVE_PHOTO=3;

    private Uri imageUri;

    private List<UploadImage> uploadImages;
    private String fileName;
    private UploadImage uploadImage;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj!=null)
            {
                try {
                    JSONObject object=new JSONObject(msg.obj.toString());
                    if (object.get("code").equals("1"))
                    {
                        Toast.makeText(ShaidanActivity.this, "晒单成功，请等待审核",Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(ShaidanActivity.this, object.get("msg").toString(),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }



        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shaidan);
        bitlist=new ArrayList<>();
        strOutpic=new ArrayList<>();
        Blist=new ArrayList<>();
        uploadImages = new ArrayList<>();
        uploadImage = new UploadImage();
        InitView();
    }

    public void InitView()
    {
        photoPopupwindow = new SelectPhotoPopupwindow(this, this);


        evaluateMain= (EvaluateModle.EvaluateMain) getIntent().getSerializableExtra("shaimain");
        iv_good= (ImageView) findViewById(R.id.iv_shaidan_good);
        tv_goods= (TextView) findViewById(R.id.tv_shaidan_goodsname);
        btn_submit= (Button) findViewById(R.id.btn_shai_submit);
        iv_shai1= (ImageView) findViewById(R.id.iv_shaidan_1);
        iv_shai2= (ImageView) findViewById(R.id.iv_shaidan_2);
        iv_shai3= (ImageView) findViewById(R.id.iv_shaidan_3);
        iv_shai4= (ImageView) findViewById(R.id.iv_shaidan_4);
        ll_main= (LinearLayout) findViewById(R.id.ll_shai_main);
        et_title= (EditText) findViewById(R.id.et_shaidan_title);
        et_content= (EditText) findViewById(R.id.et_shaidan_content);
        tv_title= (TextView) findViewById(R.id.title);
        iv_back= (ImageView) findViewById(R.id.back);
        imgarray= new ImageView[]{iv_shai1, iv_shai2, iv_shai3, iv_shai4};

        Picasso.with(this).load(ConfigValue.IMG_IP+evaluateMain.getGoods_thumb()).into(iv_good);
        tv_goods.setText(evaluateMain.getGoods_name());
        btn_submit.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_shai1.setOnClickListener(this);
        iv_shai2.setOnClickListener(this);
        iv_shai3.setOnClickListener(this);
        iv_shai4.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        tv_title.setText("商品晒单");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.iv_shaidan_1:
                picstatic=1;
                photoPopupwindow.showAtLocation(ll_main, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                break;
            case R.id.iv_shaidan_2:
                picstatic=2;
                photoPopupwindow.showAtLocation(ll_main, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.iv_shaidan_3:
                picstatic=3;
                photoPopupwindow.showAtLocation(ll_main, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.iv_shaidan_4:
                picstatic=4;
                photoPopupwindow.showAtLocation(ll_main, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;

            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                takepictures();
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                cardSelect();
                break;
            case R.id.btn_shai_submit:
                if(et_content.getText().toString().equals("") || et_title.getText().toString().equals("") || Blist.size()==0)
                {
                    Toast.makeText(this,"内容不能为空",Toast.LENGTH_LONG).show();
                }else {

                    Runnable run=new Runnable() {
                        @Override
                        public void run() {
                            Map<String,Object > params=new HashMap<>();
                            params.put("key",ConfigValue.DATA_KEY);
                            params.put("rec_id",evaluateMain.getRec_id());
                            params.put("content",et_content.getText().toString());
                            params.put("title",et_title.getText().toString());
//                            for (int i=0;i<Blist.size();i++)
//                            {
//                                int j=i+1;
//                                params.put("shaidan_img"+j+"",Blist.get(i));
//                            }
                            Message msg=new Message();
                            try {
                                msg.obj= HttpFormClient.Frompost(ConfigValue.APP_IP+"msg/saveShaidan", params, uploadImages);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            handler.sendMessage(msg);
                        }
                    };

                    Thread thread=new Thread(run);
                    thread.start();


                }

                break;
            case R.id.back:
                finish();
                break;
        }

    }
    private void cardSelect() {
        Intent it = new Intent(Intent.ACTION_PICK,null);
       /* it.setType("image*//*");
        File dir = new File("/sdcard/onlineshopping/avatar/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, "newhead.jpg");
        imageUri = Uri.fromFile(file);*/
        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(it, SELECT_PICTURE);
    }
    //相机拍照获取图片
    private void takepictures() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File("/sdcard/onlineshopping/avatar/");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, "newhead.jpg");
           // filePath = file.getAbsolutePath();
            imageUri = Uri.fromFile(file);
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
           startActivityForResult(intent, PHOTO_GRAPH);
        } else
            Toast.makeText(this, "未插入SD卡", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==0)
        {
            return;
        }
        switch (requestCode)
        {
            case SELECT_PICTURE:
                startPhotoZoom(data.getData());
                String path = data.getData().getPath();
                String[] spilt = path.split("/");
                fileName = spilt[spilt.length - 1].toString();
                uploadImage.setName(fileName);
                break;
            case PHOTO_GRAPH:

                startPhotoZoom(imageUri);
                break;
            case SAVE_PHOTO:
                showPhoto(data);
                break;

        }


    }
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, SAVE_PHOTO);
    }

    private void showPhoto(Intent data) {
        if (data != null){
            Bundle extras = data.getExtras();
            Bitmap bitmap = extras.getParcelable("data");
            if (bitmap != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] data2 = baos.toByteArray();
                if (bitlist.size()<4)
                {
                    bitlist.add(bitmap);
                    Blist.add(data2);
                    uploadImage.setData(data2);
                    uploadImages.add(uploadImage);

                }else {
                    bitlist.set(picstatic-1,bitmap);
                    Blist.set(picstatic-1,data2);
                    uploadImage.setData(data2);
                    uploadImages.add(uploadImage);
                }
                for (int i=0;i<bitlist.size();i++)
                {
                    imgarray[i].setImageBitmap(bitlist.get(i));
                }



                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }else {
            Toast.makeText(ShaidanActivity.this, "选择为空！", Toast.LENGTH_SHORT).show();
        }
    }
}
